using System;
using Kassandra.Core.Infrastructure.ResourceManagement;
using Kassandra.Core.Repositories;

namespace Kassandra.WindowsUI.Presenters
{
    public class AddNewImagePresenter
    {
        private readonly ICheckForExistingImageByAssignedCharacter _checkForExistingImageByAssignedCharacter;
        private readonly IImageRepository _imageRepository;
        private readonly IAddNewImageView _view;

        public AddNewImagePresenter(IAddNewImageView view)
            : this(new CheckForExistingImageByAssignedCharacter(), new ImageRepository(), view)
        {
        }

        public void SaveClick(object sender, EventArgs e)
        {
            Save(_view.SourceFile, _view.AssociatedCharacter);
        }

        public AddNewImagePresenter(ICheckForExistingImageByAssignedCharacter checkForExistingImageByAssignedCharacter,
                                    IImageRepository imageRepository, IAddNewImageView view)
        {
            _checkForExistingImageByAssignedCharacter = checkForExistingImageByAssignedCharacter;
            _imageRepository = imageRepository;
            _view = view;
        }

        public void Save(string fileNameAndPathToBeSaved, char? characterAssociatedWithImage)
        {
            try
            {
                if (characterAssociatedWithImage == null)
                {
                    _view.ShowMessage(MessageManagement.For("AssociatedCharValue"));
                    return;
                }

                if (string.IsNullOrEmpty(fileNameAndPathToBeSaved))
                {
                    _view.ShowMessage("You must enter the image file you want to add.");
                    return;
                }

                if (_checkForExistingImageByAssignedCharacter.AgainstTheCharacter(characterAssociatedWithImage.Value))
                {
                    _view.ShowMessage(
                        "This character already has an image associated with it. Please select another character to associate with this image.");
                    return;
                }

                _imageRepository.Save(fileNameAndPathToBeSaved, characterAssociatedWithImage.Value);

                _view.ShowMessage("Image added");

                _view.Close();                
            }
            catch(Exception ex)
            {
                _view.ShowMessage(ex.ToString());
            }
        }
    }
}